from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
import os

from html import CheckBox, DropDown, MultiSelect, RadioButton #importing the html wrappers.
import validate #import validation
import tables
import main
import datetime
import staticInits 
import cgi #for escaping html chars in forms
import re

class Course(object):
    """
    Class helps with hard coding of table for this first iteration. Will probably be removed in 
    future iterations when google data store is used.
    """
    def __init__(self, course_name, course_number):
        "Obvious constructor."
        self.course_name = course_name
        self.course_number = course_number


class AddCourse(webapp.RequestHandler):
    """
    This class deals with the admin add classes view.
    """

    
    def __init__(self):
        webapp.RequestHandler.__init__(self) #parent constructor call
        

        #DB CALLS
        self.courses1 = []
        
        
        #building dictionaries, keyed with name attributes which are gauranteed unique to each entry
        for row in db.GqlQuery("SELECT * FROM Course"): self.courses1.append(Course(row.name, row.identifier))   

        
    def get(self):
        """
        Calls renderTemplate() for this class.
        """
        self.notValidated = dict()
        self.renderTemplate()

    def post(self):
        """
        Calls renderTemplate() for this class.
        """

        self.notValidated = dict()
        self.notValidated['cNum'] = ""
        self.notValidated['cName'] = ""


        clicked = self.request.get('submit', default_value="default")
            
        # adds this instructor to datastore and immediately displays it in instructor list
        if clicked == 'Add Course' :
            course = self.request.get('courseName')
            courseNum = self.request.get('courseNumber').upper()
            vCourseNumber = validate.validateCourseNumber(courseNum)
            vCourse = validate.validateFreeText(course)
            uniqueCourse = validate.validateUniqueCourse( courseNum, course )
            if vCourseNumber and vCourse and uniqueCourse:
                
                newCourse = tables.Course( name = course, identifier = courseNum )
                newCourse.put()
                self.courses1.append(Course(course, courseNum))
            else :
                if not vCourseNumber :
                    self.notValidated['cNum'] = courseNum
                    self.notValidated['cName'] = course
                    self.response.out.write('<br><font color="red">Please enter a valid course number.</font><br />')
            
                if not vCourse :
                    self.notValidated['cName'] = course
                    self.notValidated['cNum'] = courseNum
                    self.response.out.write('<br><font color="red">Please enter a valid course name.</font><br />')
                
                if not uniqueCourse :
                    self.notValidated['cName'] = course
                    self.notValidated['cNum'] = courseNum
                    self.response.out.write('<br><font color="red">It appears that this course is already on the list. Please enter a unique course. Remember, every course must have a unique name. </font><br />')

            
        self.__init__()
        self.renderTemplate()
    
    def renderTemplate(self, addValid = "") :
        """
        Renders the Template setup.html for this class.
        """
        
        self.courses1.sort(key = lambda x : x.course_name.lower() )

        #setting up template dictionary
        templateValues = {
            #'table' : table
            'courses1' : self.courses1,
            'badCNum' : self.notValidated['cNum'] if 'cNum' in self.notValidated else "",
            'badCName' : self.notValidated['cName'] if 'cName' in self.notValidated else ""

            }


        #telling it to use the template
        path = os.path.join(os.path.dirname(__file__), 'addCourse.html')
        self.response.out.write(template.render(path, templateValues))



application = webapp.WSGIApplication([('/admin/addCourse', AddCourse)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

